package uk.co.jonlt.AndBusTest;

import android.app.Activity;
import android.content.Intent;

import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;

import android.util.Log;
import android.widget.ListView;
import android.widget.TextView;

import android.view.View;
import android.view.View.OnClickListener;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import uk.co.jonlt.AndBusTest.R;
import uk.co.jonlt.AndBusTest.Bus;
import uk.co.jonlt.AndBusTest.BusAdapter;

public class AndBusActivity extends Activity implements OnClickListener
{
	
	TextView text;
	List<Bus> listOfBus;
	BusAdapter adapter;
	ListView list;
	Object main;
	Timer timer;
	boolean processing = false;
	
	GetXMLTask tsk = new GetXMLTask();
	
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
                
        list = (ListView) findViewById(R.id.ListView01);
        list.setClickable(true);
        
        listOfBus = new ArrayList<Bus>();
        listOfBus.add(new Bus("131", "3 mins", "Tooting Broadway"));
        listOfBus.add(new Bus("76", "4 mins", "Clapham Junction"));
        listOfBus.add(new Bus("213", "11 mins", "New Malden"));

        adapter = new BusAdapter(this, listOfBus);

        list.setAdapter(adapter);
        
        Log.i("*** ","Before loading");
        
        View searchButton = findViewById(R.id.search_button);
        searchButton.setOnClickListener(this);
        
        //GetXMLTask tsk = new GetXMLTask();
        
        
        
        //tsk.execute("http://jonl-t.co.uk/tfl/countdown/arrivals/54775");
        
        //toCallAsync(); //replaces the above 2
    
        
		//new GetXMLTask().execute("http://services.jonl-t.co.uk/countdown/arrivals/stop/54775");
		
    }
    

	/** Called when the activity is paused. **/
    @Override
    public void onPause()
    {
    	Log.i("INFO","OnPaused");
    	timer.cancel();
    	super.onPause();
    } 
    
    /** Called when the activity starts **/ 
    @Override
    public void onResume() 
    {
    	Log.i("INFO","OnResume");
    	toCallAsync();
    	super.onResume();
    } 
    
    public void toCallAsync()
    {
    	TimerTask doAsync;
    	final Handler handler = new Handler();
    	timer = new Timer();
    	
    	doAsync = new TimerTask()
    	{
    		@Override
    		public void run()
    		{
    			handler.post(new Runnable()
    			{
    				public void run()
    				{
    					try
    	    			{
    	    				GetXMLTask tsk = new GetXMLTask();
    	    				tsk.execute("http://jonl-t.co.uk/tfl/countdown/arrivals/47140");
    	    			}
    	    			catch (Exception e)
    	    			{}
    				}
    			});
    		
    		}
    	};
    	timer.schedule(doAsync,0,2000);
    			
    }
    
    public class GetXMLTask extends AsyncTask<String, Void, String>
    {
    	@Override
    	protected String doInBackground(String... params) 
    	{
    		String url = params[0];
    		Log.i("-_-", "Running task");
    		String retString = null;
    		try
    		{
    			URL pcode = new URL(url);
    			HttpURLConnection http = (HttpURLConnection)pcode.openConnection();
    			InputStream in = new BufferedInputStream(http.getInputStream());
    			
    			BufferedReader r = new BufferedReader(new InputStreamReader(in));
    			StringBuilder total = new StringBuilder();
    			String line;
    			while ((line = r.readLine()) != null) {
    			    total.append(line);
    			}
    			retString = total.toString();
    			
    			Log.i("+++","Got Data");

    		}
    		catch (Exception ex)
    		{
    			Log.i("Exception", ex.getMessage());
    		}
    		return retString;
    	}
    	

		@Override
    	protected void onPostExecute(String result)
    	{

    		Buses b = new Buses();
    		try
    		{
    			b.Load(result);
    			List<Bus> busList = b.buses;
    		
    			listOfBus.clear();
    			listOfBus.addAll(busList);
    		
    			//listOfBus.add(new Bus("99", "1 mins", "New York"));
    			//listOfBus.add(new Bus("213", "11 mins", "New Malden"));
    		
    			adapter.notifyDataSetChanged();
    			//list.postInvalidate();
    			//adapter = new BusAdapter(this, listOfBus);
    			Log.i("???","Loaded data");
    		}
    			
    		catch (Exception ex)
    		{
    			Log.i("###","Load failed");
    		}
    
    	}

    }

	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()){
		case R.id.search_button:
			Intent i = new Intent(this,SearchActivity.class);
			startActivity(i);
			break;
		}
		
	}
}
